﻿param($startTime,$endTime,$exportPath)

$parentPath=(Split-Path $PSCommandPath -Parent)
$collectionConfiguration=Import-Csv -Delimiter "^" -Path .\EventCollectionConfigurations\ClientEventLogsCollection.csv


$computers=(Get-ADComputer -Filter {(name -notlike "*v-*")}).Name | Sort-Object




$scriptBlock= 
    {
        param($providerName,$computerName,$startTime,$endTime,$exportPath,$excludedEventIds)

        Import-Module -Force -DisableNameChecking $using:parentPath\libWindowsEvent.psm1
        Import-Module -Force -DisableNameChecking $using:parentPath\..\BuildDeployment\libAssertion.psm1

        if($startTime -eq $null)
        {
            if(Test-Path -Path $exportPath\Tracking\$computerName`_$providerName.txt)
            {
                $startTime=Get-Content $exportPath\Tracking\$computerName`_$providerName.txt
            }
            else
            {
                $startTime=(Get-Date).Subtract([Timespan]::FromDays(1825)).ToString("yyyy-MM-dd")
            }
        }

        if($endTime -eq $null)
        {
            $endTime=(Get-Date).ToString("yyyy-MM-dd")
        }

        if($computerName -inotlike "*v-*")
        {
            $connectionTest=Test-Connection -Count 1 -ComputerName $computerName -ErrorAction SilentlyContinue
            if($connectionTest)
            {
                try
                {
                    Write-Output "Checking Remote Registry on $computerName..."
                    $remoteRegistryService=Get-Service -ComputerName $computerName -Name RemoteRegistry -ErrorAction SilentlyContinue
                    if($remoteRegistryService.Status -eq "Stopped")
                    {
                        Write-Output "Starting service on $computerName..."
                        Get-Service -ComputerName $computerName -Name RemoteRegistry -ErrorAction SilentlyContinue | Start-Service -ErrorAction SilentlyContinue
                        Write-Output "Done!"
                    }   
                    $remoteRegistryService=Get-Service -ComputerName $computerName -Name RemoteRegistry -ErrorAction SilentlyContinue
                }
                catch
                {
                    Write-Output $_.Message
                }

                if($remoteRegistryService.Status -eq "Running")
                {
                    Write-Output "Collecting application errors on $computerName from $startTime to $endTime"
                    Assert-Directory -Path "$exportPath\$providerName"
                    Assert-Directory -Path "$exportPath\Tracking"
                    Get-ComputerEvent -providerName $providerName -computerName $computerName -startTime $startTime -endTime $endTime -excludedEventIds $excludedEventIds | Parse-WindowsEvent | Export-Csv -Path $exportPath\$providerName\$computerName.csv -Delimiter "^" -Append -NoTypeInformation
                    $endTime | Set-Content -Path $exportPath\Tracking\$computerName`_$providerName.txt -Force
                    
                    
                }
                else
                {
                    Write-Output "Remote registry is not running on $computerName"
                }
            }
            else
            {
                Write-Output "Cannot reach $computerName"
            }
        }
        else
        {
            Write-Output "$computerName is a service name,skipping."
        }
    }

foreach($computerName in $computers)
{
    foreach($collection in $collectionConfiguration)
    { 
        $jobName="Gather application events "+ $collection.ProviderName +" on $computerName"

        $jobStarted=$false

        while(-not $jobStarted)
        {
            $activeJobCount=(Get-Job -Name "Gather application events*" | Where {$_.State -eq "Running"} | Measure-Object).Count
            if($activeJobCount -le 30)
            {
                Start-Job -Name $jobName -ScriptBlock $scriptBlock -ArgumentList $collection.ProviderName,$computerName,$startTime,$endTime,$exportPath,$collection.ExcludedEventIds
                $jobStarted=$true
            }
            else
            {
                Start-Sleep -Seconds 5
            }
        }
    }
}


do
{
    Get-Job "Gather application events*"| Receive-Job
    Get-Job "Gather application events*" | where {$_.State -eq "Completed"} | Remove-Job
    Start-Sleep -Seconds 15   
}
while(((Get-Job -Name "Gather application events*" | Where {$_.State -eq "Running"} | Measure-Object).Count) -gt 0)
        
foreach($collection in $collectionConfiguration)
{
    $providerName=$collection.ProviderName
    Get-ChildItem $exportPath\$providerName\*.csv | ForEach-Object {Import-Csv -Delimiter "^"   $_} | Export-Csv -Delimiter "^" -NoTypeInformation $exportPath\$providerName.csv -Force
}